import React, { useState, useEffect } from 'react';
import { history } from 'umi'
import { Table, Button, Modal, Tag, Form, message, Card } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { ExclamationCircleOutlined } from '@ant-design/icons';
import OperaPrompt from '@/components/OperaPrompt'
import moment from 'moment';
import request from '@/utils/request';
import SaveView from './save';

const confirm = Modal.confirm;
export default () => {
  const [visable, setVisable] = useState(false);
  const [tableData, setTableData] = useState({ list: [], total: 0 });
  const [current, setCurrent] = useState(1);
  const [form] = Form.useForm();
  const [id, setId] = useState(0);

  const redirect = (activityId: number) => {
    return () => {
      history.push('/promote/shop/sec-kill/goods', { activityId });
    }
  };

  const columns: any = [
    {
      title: '活动名称',
      dataIndex: 'title',
      render: (text: any) => text,
    },
    {
      title: '开始时间',
      dataIndex: 'start_time',
      render: (text: any) => <Tag color="green">{text}</Tag>,
      align: 'center',
    },
    {
      title: '结束时间',
      dataIndex: 'end_time',
      render: (text: any) => <Tag color="green">{text}</Tag>,
      align: 'center',
    },
    {
      title: '操作',
      width: '360px',
      align: 'center',
      render: (text: any, record: any) => (
        <>
          {
            record.enable ?
              <Button danger size="small" onClick={clearCache(record.id)} >关闭</Button> :
              <Button type="primary" size="small" onClick={makeCache(record.id)}>开启</Button>
          }
          <Button size="small" onClick={redirect(record.id)} style={{ marginLeft: "8px" }}>
            查看商品
          </Button>
          <Button
            size="small"
            type="primary"
            ghost
            onClick={edit(record.id)}
            style={{ margin: '0 8px' }}
          >
            编辑
          </Button>
          <Button size="small" danger onClick={destroy([record.id])}>
            删除
          </Button>
        </>
      ),
    },
  ];

  const makeCache = (activityId: number) => {
    return () => {
      request(`/promote/sec-kill/activity-cache-make?activityId=${activityId}`, {
        method: 'POST'
      }).then((result) => {
        if (result.code === 200) {
          message.success(result.message, 1, () => {
            close()
          })
        }
      })
    }
  }
  const clearCache = (activityId: number) => {
    return () => {
      request(`/promote/sec-kill/activity-cache-clear?activityId=${activityId}`, {
        method: 'Delete'
      }).then((result) => {
        if (result.code === 200) {
          message.success(result.message, 1, () => {
            close()
          })
        }

      })
    }
  }

  const getList = (params: any = {}) => {
    request(`/promote/sec-kill/activity-list`, {
      params: { pageSize: 10, current, status, ...params },
    }).then((result) => {
      const { list, total } = result.data
      setTableData({ list, total });
    })
  };
  useEffect(() => {
    getList();
  }, []);

  const closeModal = () => {
    setVisable(false);
  };

  const destroy = (ids: any[]) => {
    return () => {
      confirm({
        title: 'Do you Want to delete these items?',
        icon: <ExclamationCircleOutlined />,
        onOk() {
          request(`/promote/sec-kill/activity-destroy`, {
            method: 'Delete',
            params: { ids },
          }).then((result) => {
            message.success('删除成功');
            getList();
          });
        },
      });
    };
  };

  const edit = (id: number) => {
    return () => {
      setId(id);
      setVisable(true);
      request(`/promote/sec-kill/activity/${id}`).then((result) => {
        const data = result.data;
        data.start_time = moment(data.start_time, 'YYYY-MM-DD HH:mm:ss');
        data.end_time = moment(data.end_time, 'YYYY-MM-DD HH:mm:ss');
        form.setFieldsValue(data);
      })
    };
  };

  return (
    <PageHeaderWrapper title={false}>
      <Card bordered={false}>
        <OperaPrompt dataList={[
          "展示了秒杀时间段列表",
          "可对时间段进行新增/编辑/删除/查看详情操作"
        ]} />
        <div style={{ margin: "5px 0 6px" }}>
          <Button
            type="primary"
            onClick={() => {
              form.resetFields();
              setVisable(true);
            }}
          >
            添加活动
        </Button>
          <Button onClick={() => {
            history.push('/promote/shop')
          }} style={{ marginLeft: "6px" }}>返回</Button>
        </div>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={tableData.list}
          pagination={{ total: tableData.total }}
        />
        <Modal
          closable={false}
          width="60%"
          visible={visable}
          onOk={() => form.submit()}
          onCancel={closeModal}
          getContainer={false}
        >
          <SaveView form={form} close={closeModal} getList={getList} id={id} />
        </Modal>
      </Card>
    </PageHeaderWrapper>
  );
};
